package com.cwits.wifi.ui.fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseFragment;
import com.cwits.wifi.base.MyGridView;
import com.cwits.wifi.data.beans.FileInfo;
import com.cwits.wifi.ui.activity.MainActivity;
import com.cwits.wifi.ui.activity.PhotoActivity;
import com.cwits.wifi.ui.dialog.TwoDialog;
import com.cwits.wifi.util.AppUtil;
import com.cwits.wifi.util.BitmapCache;
import com.cwits.wifi.util.ThreadPoolManager;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class PhotoFragment extends BaseFragment implements View.OnClickListener {
    private View mView;
    private ListView mListView;
    private RelativeLayout mRlRight, mRlBottom;
    private LinearLayout mLlNoPhoto;
    private ImageView mImRight;
    private FileAdapter mAdapter;
    private MainApplication mApplication;
    private String defaultPath;
    private List<FileInfo> allDataInfoList = null;
    private List selectList;
    private List dataInfoList = null;
    private Map<String, List<FileInfo>> mPhotoMap = null;
    private SyncResourceLoader syncResourceLoader = new SyncResourceLoader();
    private CheckBox mCbSelectAll;
    private BitmapCache mBitmapCache;
    private boolean isSelect = false;
    HashMap<String, Boolean> state;
    private MainActivity mainAct;
    private TwoDialog twoDialog;
    private int start = -1, end = -1;
    private boolean mIsTouchUpdate = false;
    public PhotoFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_photo, container, false);

        init();
        //initData();
        return mView;
    }


    /**
     * 取消选择
     */
    private void closeSelect() {
        mRlBottom.setVisibility(View.GONE);
        mainAct.selectAllT();
        mCbSelectAll.setChecked(false);
        isSelect = false;
    }

    /**
     * 进入选择
     */
    private void openSelect() {
        mRlBottom.setVisibility(View.VISIBLE);
        mainAct.selectAllF();
        isSelect = true;
    }

    public void selectAll() {

        if (isSelect) {
            //取消选择模式
            closeSelect();
            mAdapter.notifyDataSetChanged();
        } else {
            //进入选择模式
            openSelect();
            state.clear();
            selectList.clear();
            mAdapter.notifyDataSetChanged();

        }
        //showToastLong("这是PhotoFragment");
    }

    public void initSelectAllCheckBox() {
        mCbSelectAll.setChecked(false);
    }

    public boolean getIsSelect() {
        return isSelect;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (allDataInfoList != null) {
            allDataInfoList.clear();
        }
        initInfo();
        initData();

        mAdapter.notifyDataSetChanged();
        if (mBitmapCache == null) {
            mBitmapCache = BitmapCache.getInstance();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBitmapCache != null) {
            mBitmapCache.clearCache();
            mBitmapCache = null;
        }
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        //initInfo();
        //initData();
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        //isSelect = true;
        // if (selectList != null)
        // selectList.clear();
    }

    @Override
    public void onDestroyOptionsMenu() {
        super.onDestroyOptionsMenu();
    }

    @Override
    public void onStop() {
        super.onStop();
        isSelect = false;
        if (selectList != null)
            selectList.clear();
    }


    private void initInfo() {
        defaultPath = Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo";
    }

    private void initData() {

        if (null != allDataInfoList) {
            allDataInfoList.clear();
        }

        allDataInfoList = AppUtil.getLocalFileInfo(defaultPath);

        mPhotoMap.clear();
        dataInfoList.clear();

        Iterator<FileInfo> stuIter = allDataInfoList.iterator();
        while (stuIter.hasNext()) {
            FileInfo student = stuIter.next();
            if (!student.getTitle().substring(0, 3).equals("JPG") || student.getTitle().length() != 22)
                stuIter.remove();
        }

        if (null != allDataInfoList || allDataInfoList.size() != 0) {
            for (int i = 0; i < allDataInfoList.size(); i++) {

                allDataInfoList.get(i).setPosition(i);
                if (mPhotoMap.containsKey((allDataInfoList.get(i).getCreateDate().substring(0, 8)))) {
                    mPhotoMap.get(allDataInfoList.get(i).getCreateDate().substring(0, 8)).add(allDataInfoList.get(i));
                } else {
                    List<FileInfo> photoList = new ArrayList<FileInfo>();
                    photoList.add(allDataInfoList.get(i));
                    mPhotoMap.put(allDataInfoList.get(i).getCreateDate().substring(0, 8), photoList);
                }

            }

        }
        Iterator i = mPhotoMap.entrySet().iterator();
        while (i.hasNext()) {
            Object obj = i.next();
            String key = obj.toString().substring(0, 8);
            dataInfoList.add(Integer.valueOf(key));
            System.out.print(key + "==========");
        }
        Collections.sort(dataInfoList, Collections.reverseOrder());

        if (allDataInfoList.size() == 0) {
            mListView.setVisibility(View.GONE);
            mLlNoPhoto.setVisibility(View.VISIBLE);
        }
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        syncResourceLoader.lock();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        mIsTouchUpdate = false;
                        loadImage();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        mIsTouchUpdate = true;
                        syncResourceLoader.lock();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

    }
    protected void loadImage() {

        syncResourceLoader.setLoadLimit(start, end);
        syncResourceLoader.unlock();
        start = -1;
        end = -1;

    }
    private void init() {
        mainAct = (MainActivity) getActivity();
        selectList = new ArrayList();
        mApplication = (MainApplication) this.getActivity().getApplication();
        mRlBottom = (RelativeLayout) mView.findViewById(R.id.photo_rl_bottom);
        mRlBottom.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mCbSelectAll = (CheckBox) mView.findViewById(R.id.photo_cb_select);
        mListView = (ListView) mView.findViewById(R.id.photo_listview);
        mRlRight = (RelativeLayout) mView.findViewById(R.id.photo_rl_right);
        mImRight = (ImageView) mView.findViewById(R.id.photo_im_right);
        mLlNoPhoto = (LinearLayout) mView.findViewById(R.id.photo_ll_no_photo);
        mPhotoMap = new HashMap<String, List<FileInfo>>();
        state = new HashMap<String, Boolean>();
        dataInfoList = new ArrayList();

        mAdapter = new FileAdapter();
        mRlRight.setOnClickListener(this);
        mListView.setAdapter(mAdapter);
        mCbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //全选
                    state.clear();
                    selectList.clear();
                    for (int i = 0; i < allDataInfoList.size(); i++) {
                        selectList.add(allDataInfoList.get(i).getPath());
                        state.put(allDataInfoList.get(i).getTitle(), true);

                    }
                    mAdapter.notifyDataSetChanged();

                } else {
                    //取消全选
                    state.clear();
                    selectList.clear();
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.photo_rl_right:
                if (isSelect && selectList.size() != 0) {
                    //showTwoDialog();
                    showDele();
                } else {
                    showToastLong(getString(R.string.photo_no_sel));
                }
                break;
        }
    }


    private class FileAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mPhotoMap.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(getActivity().getApplication(), R.layout.item_photo, null);
                holder = new ViewHolder();
                convertView.setTag(holder);
                // 给holder找view
                holder.tvTitle = (TextView) convertView.findViewById(R.id.item_photo_tv_title);
                holder.gvPhoto = (MyGridView) convertView.findViewById(R.id.item_photo_gv_photo);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.tvTitle.setText(changeData(String.valueOf(dataInfoList.get(position))));
            final List<FileInfo> bean = mPhotoMap.get(String.valueOf(dataInfoList.get(position)));
            //holder.gvPhoto.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(getActivity(), a * 90)));
            final PhotoAdapter mAdapter = new PhotoAdapter(bean);
            holder.gvPhoto.setAdapter(mAdapter);
            //final ViewHolder finalHolder = holder;
            holder.gvPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    CheckBox cb = (CheckBox) view.findViewById(R.id.item_photo_gv_cb_photo);
                    if (!isSelect) {
                        //点击看大图
                        cb.setVisibility(View.GONE);
                        Intent intent = new Intent(getActivity().getApplicationContext(), PhotoActivity.class);
                        if (null != bean.get(position)) {
                            intent.putExtra("photo_file", bean.get(position).getPosition() + "");
                            //getActivity().startActivityForResult(intent, 1000);
                            getActivity().startActivity(intent);

                            //调用系统
                            /*
                            Intent intent2 = new Intent(Intent.ACTION_VIEW);
                            intent2.setDataAndType(Uri.parse("file://" + bean.get(position).getPath()), "image/*");
                            if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                                startActivity(intent2);
                            }*/
                        }
                    } else {
                        cb.setVisibility(View.VISIBLE);
                        cb.setChecked(true);
                    }
                }
            });
            return convertView;
        }
    }

    private class ViewHolder {
        TextView tvTitle;
        MyGridView gvPhoto;
    }

    private class PhotoAdapter extends BaseAdapter {

        List<FileInfo> mFileInfoList;

        public PhotoAdapter(List<FileInfo> bean) {
            mFileInfoList = bean;
        }

        @Override
        public int getCount() {
            return mFileInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            //bit = BitmapFactory.decodeFile(mFileInfoList.get(position).getPath());
            ImViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(getActivity().getApplication(), R.layout.item_photo_gv, null);
                holder = new ImViewHolder();
                convertView.setTag(holder);
                // 给holder找view
                holder.cbPhoto = (CheckBox) convertView.findViewById(R.id.item_photo_gv_cb_photo);
                holder.imPhoto = (ImageView) convertView.findViewById(R.id.item_photo_gv_im_photo);

            } else {
                holder = (ImViewHolder) convertView.getTag();
            }
            if (isSelect) {
                holder.cbPhoto.setVisibility(View.VISIBLE);
                holder.cbPhoto.setChecked(state.get(mFileInfoList.get(position).getTitle()) == null ? false : true);
            } else {
                holder.cbPhoto.setVisibility(View.GONE);
            }

            syncResourceLoader.loadImage(holder, mFileInfoList.get(position), position, mFileInfoList);

                /*
                Bitmap bitmap = mBitmapCache.getBitmap(mFileInfoList.get(position).getPath());
                if (bitmap != null) {
                    holder.imPhoto.setImageBitmap(ImageCrop(bitmap));
                } else {
                    holder.imPhoto.setImageResource(R.mipmap.icon_no_pic);
                }*/



            // if (!isSelect) {
            holder.cbPhoto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        //选中 添加
                        if (!selectList.contains(mFileInfoList.get(position).getPath())) {
                            selectList.add(mFileInfoList.get(position).getPath());
                        }

                        state.put(mFileInfoList.get(position).getTitle(), true);

                    } else {
                        //未选中 删除
                        if (selectList.contains(mFileInfoList.get(position).getPath())) {
                            for (int i = 0; i < selectList.size(); i++) {
                                if (mFileInfoList.get(position).getPath().equals(selectList.get(i))) {
                                    selectList.remove(i);
                                }
                            }
                        }
                        state.remove(mFileInfoList.get(position).getTitle());
                    }
                }
            });
            //   }
            return convertView;
        }
    }

    private class ImViewHolder {
        ImageView imPhoto;
        CheckBox cbPhoto;
    }

    public static Bitmap ImageCrop(Bitmap bitmap) {

        int w = bitmap.getWidth(); // 得到图片的宽，高
        int h = bitmap.getHeight();

        int wh = w > h ? h : w;// 裁切后所取的正方形区域边长

        int retX = w > h ? (w - h) / 2 : 0;//基于原图，取正方形左上角x坐标
        int retY = w > h ? 0 : (h - w) / 2;

        //下面这句是关键
        return Bitmap.createBitmap(bitmap, retX, retY, wh, wh, null, false);
    }


    /**
     * dialog弹出2
     */

    private void showDele() {
        twoDialog = new TwoDialog(getActivity(), getString(R.string.dialog_tip), getString(R.string.photo_sel1) + " " + selectList.size() + " " + getString(R.string.photo_sel2) + "?" , deleListener);
        twoDialog.show();
    }

    private View.OnClickListener deleListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    twoDialog.dismiss();
                    handler1.sendEmptyMessageDelayed(1112, 10);

                    break;
                case R.id.dialog_btn2_rl_canale:
                    twoDialog.dismiss();
                    break;
            }
        }
    };

    public class SyncResourceLoader {

        private Object lock = new Object();

        private boolean mAllowLoad = true;

        private boolean firstLoad = true;

        private int mStartLoadLimit = 0;

        private int mStopLoadLimit = 0;

        final Handler handler = new Handler();

        private HashMap<String, SoftReference<Bitmap>> bitmapCache = new HashMap<String, SoftReference<Bitmap>>();

        public void setLoadLimit(int startLoadLimit, int stopLoadLimit) {
            if (startLoadLimit > stopLoadLimit) {
                return;
            }
            mStartLoadLimit = startLoadLimit;
            mStopLoadLimit = stopLoadLimit;
        }

        public void restore() {
            mAllowLoad = true;
            firstLoad = true;
        }

        public void lock() {
            mAllowLoad = false;
            firstLoad = false;
        }

        public void unlock() {
            mAllowLoad = true;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void loadImage(final ImViewHolder holder, final FileInfo rm, Integer t, final List<FileInfo> routeInfoList) {
            final ImViewHolder mImageUrl = holder;
            final FileInfo mRouteInfo = rm;
            final Integer mt = t;

            ThreadPoolManager.getLongPool().execute(new Runnable() {

                @Override
                public void run() {

                    if (!mAllowLoad) {
                        synchronized (lock) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    if (mAllowLoad) {
                        loadImage(holder, rm, routeInfoList);
                    }

                }

            });

        }

        private void loadImage(final ImViewHolder holder, final FileInfo rm1, final List<FileInfo> routeInfoList) {

            final FileInfo rm = rm1;
            //final Bitmap dd = loadImageFromUrl(rm.getVideo_file());
            final Bitmap bitmap1 = mBitmapCache.getBitmap(rm.getPath());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (mAllowLoad) {

                        if (bitmap1 != null) {
                            holder.imPhoto.setImageBitmap(ImageCrop(bitmap1));
                        } else {
                            holder.imPhoto.setImageResource(R.mipmap.icon_no_pic);
                        }

                    }
                }
            });
        }

    }

    private void deleFile() {


        for (int i = 0; i < selectList.size(); i++) {
            deleteFile((String) selectList.get(i));
        }


        //initData();

    }

    private void cleanList() {

        for (int i = 0; i < selectList.size(); i++) {
            for (int j = 0; j < allDataInfoList.size(); j++) {

                if (allDataInfoList.get(j).getPath().equals(selectList.get(i))) {
                    allDataInfoList.remove(j);
                }
            }
        }

        mPhotoMap.clear();
        dataInfoList.clear();
        if (null != allDataInfoList || allDataInfoList.size() != 0) {
            for (int i = 0; i < allDataInfoList.size(); i++) {

                allDataInfoList.get(i).setPosition(i);
                if (mPhotoMap.containsKey((allDataInfoList.get(i).getCreateDate().substring(0, 8)))) {
                    mPhotoMap.get(allDataInfoList.get(i).getCreateDate().substring(0, 8)).add(allDataInfoList.get(i));
                } else {
                    List<FileInfo> photoList = new ArrayList<FileInfo>();
                    photoList.add(allDataInfoList.get(i));
                    mPhotoMap.put(allDataInfoList.get(i).getCreateDate().substring(0, 8), photoList);
                }
            }
        }
        Iterator i = mPhotoMap.entrySet().iterator();
        while (i.hasNext()) {
            Object obj = i.next();
            String key = obj.toString().substring(0, 8);
            dataInfoList.add(Integer.valueOf(key));
            System.out.print(key + "==========");
        }
        Collections.sort(dataInfoList, Collections.reverseOrder());

        if (allDataInfoList.size() == 0) {
            mListView.setVisibility(View.GONE);
            mLlNoPhoto.setVisibility(View.VISIBLE);
        }
    }

    private Handler handler1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1111:
                    cleanList();
                    closeSelect();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 1112:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            deleFile();// 耗时的方法
                            handler1.sendEmptyMessage(1111);// 执行耗时的方法之后发送消给handler
                        }
                    }).start();


                    break;
            }
        }
    };


}
